// pages/home-music/index.js
import {
  rankingStore,
  rankingMap,
  playerStore
} from "../../store/index"


import {
  getBanners,
  getSongMenu
} from "../../service/api_music"
import queryRect from "../../utils/query-rect"
import throttle from "../../utils/throttle"

const throttleQueryRect = throttle(queryRect, 10, {
  trailing: true
})

Page({

  /**
   * 页面的初始数据
   */
  data: {
    swiperHeight: 0,
    banners: [],
    hotSongMenu: [],
    recommendSongMwnu: [],
    rankings: {
      0: {},
      2: {},
      3: {}
    },
    currentSong: {},
    isPlaying: false,
    playAnimState: "paused"
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    playerStore.dispatch("playMusicWithSongIdAction", {
      id: 1901371647
    })

    //获取页面数据
    this.getPageData()

    //获取共享数据请求
    rankingStore.dispatch("getRankingDateAction")

    //从store中获取共享数据
    this.setupPlayerStoreListener()
  },

  //数据请求
  getPageData: function () {
    getBanners().then(res => {
        this.setData({
          banners: res.banners
        })
      }),
      getSongMenu().then(res => {
        this.setData({
          hotSongMenu: res.playlists
        })
      }),
      getSongMenu('说唱').then(res => {
        this.setData({
          recommendSongMwnu: res.playlists
        })
      })
  },


  //事件处理
  handleSearchClick: function () {
    wx.navigateTo({
      url: '/pages/detail-search/index',
    })
  },

  handleSwiperImageLoaded: function () {
    //获取图片的高度

    //使用节流函数进行性能优化
    throttleQueryRect(".swiper-image").then((res) => {
      const rect = res[0]
      this.setData({
        swiperHeight: rect.height
      })
    })
  },

  handleMoreClick: function () {
    this.navigateToDetailSongsPage("hotRanking")
  },

  handleRankingItemClick: function (event) {
    const idx = event.currentTarget.dataset.idx
    const rankingName = rankingMap[idx]
    this.navigateToDetailSongsPage(rankingName)
  },

  navigateToDetailSongsPage: function (rankingName) {
    wx.navigateTo({
      url: `/pages/detail-songs/index?ranking=${rankingName}&type=rank`,
    })
  },

  handleSongItemClick: function (event) {
    const index = event.currentTarget.dataset.index
    playerStore.setState("playListSongs", this.data.recommendSongs)
    playerStore.setState("playListIndex", index)
  },

  handlePlayBtnClick: function (event) {
    playerStore.dispatch('changeMusicPlayStatusAction', !this.data.isPlaying)

  },

  handlePlayBarClick: function () {
    wx.navigateTo({
      url: '/pages/music-player/index?id=' + this.data.currentSong.id,
    })
  },

  setupPlayerStoreListener: function () {
    //排行榜监听
    rankingStore.onState("hotRanking", (res) => {
      if (!res.tracks) return
      const recommendSongs = res.tracks.slice(0, 6)
      this.setData({
        recommendSongs
      })
    })

    rankingStore.onState("newRanking", this.getRankingHandler(0))
    rankingStore.onState("originRanking", this.getRankingHandler(2))
    rankingStore.onState("upRanking", this.getRankingHandler(3))

    //播放器监听
    playerStore.onStates(['currentSong', 'isPlaying', 'playModeIndex'], ({
      currentSong,
      isPlaying,
      playModeIndex
    }) => {
      if (currentSong) this.setData({
        currentSong
      })

      if (typeof isPlaying !== 'undefined') this.setData({
        isPlaying,
        playAnimState: isPlaying ? "running" : "paused"
      })

      if (typeof playModeIndex !== 'undefined') {
        this.setData({
          playModeIndex
        })
      }
    })
  },

  getRankingHandler: function (idx) {
    return (res) => {
      //得到榜单前三条数据
      if (Object.keys(res).length === 0) return
      const name = res.name
      const coverImgUrl = res.coverImgUrl
      const playCount = res.playCount
      const songList = res.tracks.slice(0, 3)
      const rankingObj = {
        name,
        coverImgUrl,
        playCount,
        songList
      }
      const newRankings = {
        ...this.data.rankings,
        [idx]: rankingObj
      }
      this.setData({
        rankings: newRankings
      })
    }
  }
})